package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.dto.UserLoginDTO;
import com.example.demo.dto.UserLoginResponseDTO;
import com.example.demo.dto.UserRegisterDTO;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<UserLoginResponseDTO> login(@RequestBody UserLoginDTO loginDTO) {
        return Result.success(userService.login(loginDTO));
    }

    @PostMapping("/register")
    public Result<UserLoginResponseDTO> register(@RequestBody UserRegisterDTO registerDTO) {
        return Result.success(userService.register(registerDTO));
    }

    @GetMapping("/check-usercode")
    public Result<Boolean> checkUsercode(@RequestParam String usercode) {
        return Result.success(userService.checkUsercodeExists(usercode));
    }

    @GetMapping("/check-email")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        return Result.success(userService.checkEmailExists(email));
    }

    @GetMapping("/{id}")
    public Result<UserLoginResponseDTO> findById(@PathVariable("id") Integer userId) {
        User user = userService.findById(userId);
        // 转换为UserLoginResponseDTO对象，确保包含教师的管理员角色信息
        UserLoginResponseDTO responseDTO = userService.convertToResponseDTO(user);
        return Result.success(responseDTO);
    }

    @GetMapping("/{id}/profile")
    public Result<UserLoginResponseDTO> getUserProfile(@PathVariable("id") Integer userId) {
        User user = userService.findById(userId);
        // 转换为UserLoginResponseDTO对象，确保包含教师的管理员角色信息
        UserLoginResponseDTO responseDTO = userService.convertToResponseDTO(user);
        return Result.success(responseDTO);
    }

    @GetMapping
    public Result<List<User>> findAll() {
        return Result.success(userService.findAll());
    }

    @GetMapping("/org/{orgId}")
    public Result<List<User>> findByOrgId(@PathVariable("orgId") Integer orgId) {
        return Result.success(userService.findByOrgId(orgId));
    }

    @GetMapping("/type/{userType}")
    public Result<List<User>> findByUserType(@PathVariable("userType") String userType) {
        return Result.success(userService.findByUserType(userType));
    }

    @GetMapping("/org/{orgId}/type/{userType}")
    public Result<List<User>> findByOrgIdAndUserType(
            @PathVariable("orgId") Integer orgId,
            @PathVariable("userType") String userType,
            @RequestParam(value = "includeSubOrgs", required = false, defaultValue = "false") boolean includeSubOrgs) {
        if (includeSubOrgs) {
            return Result.success(userService.findByOrgTreeAndUserType(orgId, userType));
        } else {
            return Result.success(userService.findByOrgIdAndUserType(orgId, userType));
        }
    }
    
    /**
     * 根据组织ID查询所有用户，支持包含子组织
     */
    @GetMapping("/org/{orgId}/type")
    public Result<List<User>> findByOrgId(
            @PathVariable("orgId") Integer orgId,
            @RequestParam(value = "includeSubOrgs", required = false, defaultValue = "false") boolean includeSubOrgs) {
        if (includeSubOrgs) {
            // 查询该组织及其子组织下的所有用户
            List<User> students = userService.findByOrgTreeAndUserType(orgId, "STUDENT");
            List<User> teachers = userService.findByOrgTreeAndUserType(orgId, "TEACHER");
            students.addAll(teachers);
            return Result.success(students);
        } else {
            return Result.success(userService.findByOrgId(orgId));
        }
    }
    
    /**
     * 获取待审核的教师列表
     */
    @GetMapping("/pending-teachers")
    public Result<List<User>> findPendingTeachers() {
        return Result.success(userService.findPendingTeachers());
    }
    
    /**
     * 审批教师账号
     */
    @PostMapping("/approve-teacher")
    public Result<Boolean> approveTeacher(@RequestBody Map<String, Object> request) {
        Integer userId = (Integer) request.get("userId");
        Integer approverId = (Integer) request.get("approverId");
        Boolean isApproved = (Boolean) request.get("isApproved");
        String comment = (String) request.get("comment");
        
        return Result.success(userService.approveTeacher(userId, approverId, isApproved, comment));
    }
    
    /**
     * 设置用户的管理员角色
     */
    @PutMapping("/{id}/admin-role")
    public Result<Boolean> setAdminRole(
            @PathVariable("id") Integer userId,
            @RequestBody Map<String, String> request) {
        String adminRole = request.get("adminRole");
        return Result.success(userService.setAdminRole(userId, adminRole));
    }

    @PostMapping("/change-password")
    public Result<Boolean> changePassword(@RequestBody Map<String, Object> request) {
        Integer userId = (Integer) request.get("userId");
        String oldPassword = (String) request.get("oldPassword");
        String newPassword = (String) request.get("newPassword");
        
        // 这里需要在UserService中添加相应的方法
        return Result.success(userService.changePassword(userId, oldPassword, newPassword));
    }

    @PostMapping
    public Result<User> create(@RequestBody User user) {
        return Result.success(userService.create(user));
    }

    @PutMapping("/{id}")
    public Result<User> update(@PathVariable("id") Integer userId, @RequestBody User user) {
        user.setUserId(userId);
        return Result.success(userService.update(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable("id") Integer userId) {
        return Result.success(userService.deleteById(userId));
    }
} 